package receipe.pushing;

import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import receipe.Recipe;

public class RecipeAllDataToPush {

	LinkedList<Recipe> recipes = new LinkedList<Recipe>();

	private Document parse(File xmlFile) throws DocumentException {

		/** Method for document parsing */

		SAXReader reader = new SAXReader();
		Document document = reader.read(xmlFile);
		return document;
	}

	/**
	 * Method for reading data from parsed document
	 */

	public List<Recipe> loadData(File xmlFile) throws DocumentException {

		Document doc;
		try {
			doc = parse(xmlFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
			return null;
		}

		/**
		 * Doing that looking on data from xml document First we access to the
		 * root element of document
		 */
		Element root = doc.getRootElement();

		Recipe recipe = new Recipe();

		for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {

			/** Next element */

			Element recipe_element = (Element) i.next();

			for (Iterator<Element> p = recipe_element.elementIterator(); p
					.hasNext();) {
				/**
				 * Accessing to sub-element
				 */

				Element recipe_child = (Element) p.next();

				String recipe_child_name = recipe_child.getName();

				String recipe_child_value = recipe_child.getText();

				/**
				 * We check what we read and setting attributes to our classes
				 */

				if (recipe_child_name.equals("name")) {
					recipe.setName(recipe_child_value);

				} else if (recipe_child_name.equals("author")) {
					recipe.setAuthor(recipe_child_value);
				} else if (recipe_child_name.equals("recipeCategory")) {
					recipe.setRecipeCategory(recipe_child_value);
				} else if (recipe_child_name.equals("totalTime")) {
					recipe.setTotalTime(recipe_child_value);
				} else if (recipe_child_name.equals("prepTime")) {
					recipe.setPrepTime(recipe_child_value);
				} else if (recipe_child_name.equals("cookTime")) {
					recipe.setCookTime(recipe_child_value);
				} else if (recipe_child_name.equals("description")) {
					recipe.setDescription(recipe_child_value);
				} else if (recipe_child_name.equals("ingredients")) {
					recipe.setIngredients(recipe_child_value);
				} else if (recipe_child_name.equals("recipeInstructions")) {
					recipe.setRecipeInstructions(recipe_child_value);
				} else if (recipe_child_name.equals("recipeYield")) {
					recipe.setRecipeYield(recipe_child_value);
				}
			}
		}

		recipes.add(recipe);

		/** List with all recipes */
		return recipes;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (Recipe recipe : recipes) {
			sb.append(recipe.toString() + "\n");
		}
		return sb.toString();
	}
}
